//
//  LocalViewController.swift
//  Trill
//
//  Created by 顾钱想 on 2019/11/10.
//  Copyright © 2019 顾钱想. All rights reserved.
//

import UIKit
import MJRefresh
import SDWebImage
import CHTCollectionViewWaterfallLayout
class LocalViewController: ViewController<LocalViewModel> {
    var items:[LocalItem] = []
    var lastId: String = ""

//    private lazy var layout: CWaterFallLayout = {
//       let lay = CWaterFallLayout()
//       lay.columnSpacing = 10
//       lay.lineSpacing = 5
//       lay.sectionLeft = 5
//       lay.sectionRight = 5
//       lay.delegate = self
//       return lay
//    }()

    private lazy var layout: CHTCollectionViewWaterfallLayout = {
       let lay = CHTCollectionViewWaterfallLayout()
       lay.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
       lay.columnCount = 2
       return lay
    }()
    lazy var collectionView: UICollectionView = {
        let _collectionView = UICollectionView(frame: view.bounds,collectionViewLayout: layout)
        _collectionView.register(UINib.init(nibName: "LocalCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: identifier)
        _collectionView.backgroundColor = .white
        _collectionView.delegate = self
        _collectionView.dataSource = self
        _collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
                self?.request(position: 0)
            })
        _collectionView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { [weak self] in
                self?.request(position: self?.items.count ?? 0)
            })
        return _collectionView
    }()
    let identifier = "LocalCollectionViewCell"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(collectionView)
        self.collectionView.mj_header.beginRefreshing()
    }
    func request(position: Int) {
           HomeApi.waterfall(position: position, lastId: lastId)
           .request()
           .mapObject(LocalData.self)
           .subscribe(onSuccess: { [weak self] in
                 if position == 0{
                    self?.items = $0.items
                 } else {
                    self?.items += $0.items
                 }
                 self?.lastId = $0.lastId
                 self?.collectionView.reloadData()
                 if self?.collectionView.mj_header != nil {
                    self?.collectionView.mj_header.endRefreshing()
                 }
                 if self?.collectionView.mj_footer != nil {
                    self?.collectionView.mj_footer.endRefreshing()
                 }
           }, onError: { [weak self] _ in
                 if self?.collectionView.mj_header != nil {
                    self?.collectionView.mj_header.endRefreshing()
                 }
                 if self?.collectionView.mj_footer != nil {
                    self?.collectionView.mj_footer.endRefreshing()
                 }
           })
           .disposed(by: rx.disposeBag)
       }
}

//// MARK: - UICollectionViewDelegate
extension LocalViewController: UICollectionViewDelegate, UICollectionViewDataSource,CHTCollectionViewDelegateWaterfallLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
        let item = items[indexPath.row]
        if (item.imgSize != nil) {
          ///等比例计算
          let h = CGFloat(item.imgSize?.height ?? 200)
          let w = CGFloat(item.imgSize?.width ?? 200)
            let rh = (UIScreen.main.bounds.width - 20) / 2 / w * h > 200 ? (UIScreen.main.bounds.width - 20) / 2 / w * h : 200
          return CGSize.init(width: (UIScreen.main.bounds.width - 20) / 2, height: rh)
        }
        let height = 200 + arc4random()%100 + 1
        return CGSize.init(width: (UIScreen.main.bounds.width - 20) / 2, height: CGFloat(height));
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        items.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell =  collectionView.dequeueReusableCell(withReuseIdentifier: identifier,
        for: indexPath) as! LocalCollectionViewCell
        let item = items[indexPath.row]
        if item.entry?.gif?.isNotEmpty ?? false {
            let urls = item.entry?.gif?.components(separatedBy: "?")
            let url = URL(string: urls?.first ?? "")
            cell.img.sd_setImage(with: url, placeholderImage: UIImage(), options: SDWebImageOptions.refreshCached) {[weak self] (img, error, SDImageCacheType, imageURL) in
                if (img != nil) {
                    if self?.items[indexPath.row].imgSize != img?.size {
                        self?.items[indexPath.row].imgSize = img?.size
                        self?.collectionView.reloadItemsAtIndexPaths([indexPath], animationStyle: .none)

                    }
                }
            }
        } else if  item.entry?.photo?.isNotEmpty ?? false{
            let urls = item.entry?.photo?.components(separatedBy: "?")
            let url = URL(string: urls?.first ?? "")
            cell.img.sd_setImage(with: url, placeholderImage: UIImage(), options: SDWebImageOptions.refreshCached) {[weak self] (img, error, SDImageCacheType, imageURL) in
                if (img != nil) {
                    if self?.items[indexPath.row].imgSize != img?.size {
                       self?.items[indexPath.row].imgSize = img?.size
                       self?.collectionView.reloadItemsAtIndexPaths([indexPath], animationStyle: .none)
                   }
                }
           }
        } else {
            cell.img.image = UIImage(named: "default_slider_img.png")
        }

        cell.item = items[indexPath.row]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("\(indexPath.row)")
    }

}


